package com.hyk.commonLib.common.utils.dataBinding.bindingAdapter;

import android.text.Editable;
import android.widget.EditText;

import androidx.databinding.BindingAdapter;

import com.hyk.commonLib.common.utils.rx.EmptyObserver;
import com.jakewharton.rxbinding4.widget.RxTextView;
import com.jakewharton.rxbinding4.widget.TextViewAfterTextChangeEvent;
import com.jakewharton.rxbinding4.widget.TextViewBeforeTextChangeEvent;

import org.jetbrains.annotations.NotNull;

/**
 * Created by 贺玉琨 on 2020/7/21.
 */
public class TextChangeAdapter {
    @BindingAdapter("beforeTextChanged")
    public static void setBeforeTextChanged(EditText view, BeforeTextChangedListener listener) {
        RxTextView.beforeTextChangeEvents(view)
                .subscribe(new EmptyObserver<TextViewBeforeTextChangeEvent>() {
                    @Override
                    public void onNext(@NotNull TextViewBeforeTextChangeEvent event) {
                        listener.onEvent(event.getText(), event.getStart(), event.getCount(), event.getAfter());
                    }
                });
    }

    @BindingAdapter("onTextChanged")
    public static void setOnTextChanged(EditText view, OnTextChangeListener listener) {
        RxTextView.textChanges(view)
                .subscribe(new EmptyObserver<CharSequence>() {
                    @Override
                    public void onNext(@NotNull CharSequence charSequence) {
                        listener.onChange(charSequence);
                    }
                });
    }

    @BindingAdapter("afterTextChanged")
    public static void setAfterTextChanged(EditText view, AfterTextChangedListener listener) {
        RxTextView.afterTextChangeEvents(view)
                .subscribe(new EmptyObserver<TextViewAfterTextChangeEvent>() {
                    @Override
                    public void onNext(@NotNull TextViewAfterTextChangeEvent event) {
                        listener.onEvent(event.getEditable());
                    }
                });
    }

    public interface OnTextChangeListener {
        void onChange(CharSequence charSequence);
    }

    public interface BeforeTextChangedListener {
        void onEvent(CharSequence s, int start, int count, int after);
    }

    public interface AfterTextChangedListener {
        void onEvent(Editable s);
    }
}
